package com.cyy.dyeing.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cyy.dyeing.common.DataStatusEnum;
import com.cyy.dyeing.common.DyeingConstants;
import com.cyy.dyeing.common.Result;
import com.cyy.dyeing.dto.PasswordDto;
import com.cyy.dyeing.dto.UserDto;
import com.cyy.dyeing.exception.BusinessException;
import com.cyy.dyeing.model.Role;
import com.cyy.dyeing.model.User;
import com.cyy.dyeing.service.RoleService;
import com.cyy.dyeing.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author: cyy
 * @Date: 2024/7/22
 * 用户模块控制器类
 */
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    /**
     * 添加用户
     * @param userDto
     * @return
     */
    @PostMapping
    public Result insertUser(@RequestBody UserDto userDto) {
        //TODO 调用业务请求
        //1. 根据传入的账号判断该账号是否已经存在
        User exist = userService.getUserById(userDto.getU_id());
        if(exist != null){
            throw new BusinessException("账号已经存在!!!");
        }
        //2. 添加
        User user = new User(userDto.getU_id(),
                userDto.getU_name(),
                DyeingConstants.USER_DEFAULT_PASSWORD,
                DataStatusEnum.UNDETERMINED.getCode());
        userService.save(user);
        return Result.ok();
    }

    /**
     * 用户列表
     * @param userDto
     * @return
     */
    @GetMapping
    public Result userList(UserDto userDto) {
        //TODO 调用业务层
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getU_status, userDto.getU_status())
                .like(userDto.getU_name() != null, User::getU_name, userDto.getU_name())
                .like(userDto.getU_id() != null, User::getU_id, userDto.getU_id());
        Page<User> pageInfo = new Page<>(userDto.getPageNum(), userDto.getPageSize());
        userService.page(pageInfo, wrapper);
        return Result.ok(pageInfo);
    }

    /**
     * 修改状态
     * @param u_id 用户 id
     * @param currentStatus 当前状态
     * @return
     */
    @PutMapping("/{u_id}/{currentStatus}")
    public Result userChangeStatus(@PathVariable String u_id,
                                   @PathVariable String currentStatus){
        String message = userService.executeChangeStatus(u_id, currentStatus);
        return Result.ok(message);
    }

    /**
     * 根据 id 删除用户
     * @param u_id
     * @return
     */
    @DeleteMapping("/{u_id}")
    public Result userDelete(@PathVariable String u_id){
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getU_id, u_id);
        User user = userService.getOne(wrapper);
        if(user == null || !user.getU_status().equals(DataStatusEnum.UNDETERMINED.getCode())){
            throw new BusinessException("账号不存在 或 该数据不允许被删除");
        }
        userService.remove(wrapper);
        return Result.ok();
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @DeleteMapping
    public Result userDelete(@RequestBody String[] ids){
        for (String id :ids) {
            userDelete(id);
        }
        return Result.ok();
    }

    /**
     * 获取角色列表
     * @param userDto
     * @return
     */
    @GetMapping("/role")
    public Result getUserRoleList(UserDto userDto){
        Page<Role> pageInfo = new Page<>(userDto.getPageNum(), userDto.getPageSize());
        //获得用户角色列表
        List<Role> roleList = roleService.findRoleList(userDto.getU_id(), DataStatusEnum.ACTIVE.getCode());
        pageInfo.setRecords(roleList);
        roleService.page(pageInfo);
        return Result.ok(pageInfo);
    }

    /**
     * 密码修改
     * @param passwordDto
     * @param clientToken
     * @return
     */
    @PutMapping("updatePwd")
    public Result updatePwd(@RequestBody PasswordDto passwordDto,
                            @RequestHeader(DyeingConstants.HEADER_USER_TOKEN)String clientToken){
        User user = userService.getUserById(passwordDto.getU_id());
        if(user == null){
            throw new BusinessException("该用户不存在");
        }else{
            if(!user.getU_pwd().equals(passwordDto.getOld_pwd())){
                throw new BusinessException("密码不一致");
            }
        }
        user.setU_pwd(passwordDto.getNew_pwd());
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(User::getU_id, user.getU_id());
        userService.update(user, updateWrapper);
        return Result.ok();
    }


}
